﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Windows.Controls;
using System.Windows.Data;
using System.Data.Objects.DataClasses;
using Common.Services;
using System.Windows;
using System.Data;
using System.ComponentModel;
using System.Windows.Controls;

namespace Common.UI.Controls
{
    public class AssociationCheckList<S, E> : DataGrid
        where S : IGenericEntityReaderService<E>, new()
        where E : EntityObject
    {

        Boolean isLoaded = false;

        public EntityCollection<E> List
        {
            get { return (EntityCollection<E>)GetValue(ListProperty); }
            set { SetValue(ListProperty, value); }
        }

        public static readonly DependencyProperty ListProperty =
            DependencyProperty.Register("List", typeof(EntityCollection<E>), typeof(AssociationCheckList<S, E>), new UIPropertyMetadata(null, new PropertyChangedCallback(List_Changed)));

        private static void List_Changed(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            //if (e.NewValue != null)
            //{
            //    AssociationCheckList<S, E> associationCheckList = (AssociationCheckList<S, E>)o;
            //    associationCheckList.SetExistingValues((EntityCollection<E>)e.NewValue);
            //}
        }

        IGenericEntityReaderService<E> _entityReader;
        public IGenericEntityReaderService<E> EntityReader
        {
            get
            {
                if (_entityReader == null)
                {
                    _entityReader = new S();
                }
                return _entityReader;
            }
        }

        public AssociationCheckList()
            : base()
        {

            this.SelectionMode = DataGridSelectionMode.Single;
            this.CanUserAddRows = false;
            this.CanUserDeleteRows = false;
            this.AutoGenerateColumns = false;
            this.SelectionUnit = DataGridSelectionUnit.Cell;

            this.Loaded += new System.Windows.RoutedEventHandler(AssociationCheckList_Loaded);
            this.CellEditEnding += new EventHandler<DataGridCellEditEndingEventArgs>(AssociationCheckList_CellEditEnding);
            this.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);

            this.AddCheckField();
            this.AddColumnDefinitions();
        }

        void AssociationCheckList_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            if (e.Column == checkField)
            {
                if (e.EditAction == DataGridEditAction.Commit)
                {
                    var checkBox = e.EditingElement as CheckBox;

                    if (checkBox.IsChecked.HasValue)
                    {
                        var entity = e.Row.Item as E;

                        if (checkBox.IsChecked.Value)
                        {
                            //checkeado
                            if (!this.List.Contains(entity))
                            {
                                this.List.Add(entity);
                            }
                        }
                        else
                        {
                            //descheckeado
                            if (this.List.Contains(entity))
                            {
                                this.List.Remove(entity);
                            }
                        }
                    }
                }
            }
        }

        private DataGridCheckBoxColumn checkField = new DataGridCheckBoxColumn();
        private void AddCheckField()
        {
            checkField.Header = "Selección";
            checkField.IsReadOnly = false;
            this.Columns.Add(checkField);
        }

        protected virtual void AddColumnDefinitions()
        {
        }

        private void LoadEntities()
        {
            this.ItemsSource = EntityReader.ReadEntities();
            isLoaded = true;
        }

        public void AddColumnDefinition(String columnName, String header)
        {
            var column = new DataGridTextColumn();

            column.Header = header;
            column.Binding = new Binding(columnName);
            column.IsReadOnly = true;
            this.Columns.Add(column);
        }

        void AssociationCheckList_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!DesignerProperties.GetIsInDesignMode(this) && !isLoaded)
            {
                this.LoadEntities();
            }
        }

        private void SetExistingValues(EntityCollection<E> list)
        {
            if (!this.isLoaded)
            {
                this.LoadEntities();
            }

            foreach (var item in list)
            {
                for (int i = 0; i < this.Items.Count; i++)
                {
                    var dataRow = this.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;

                    var entity = dataRow.Item as E;

                    var checkBox = checkField.GetCellContent(dataRow.Item) as CheckBox;

                    if (List.Contains(entity))
                    {
                        checkBox.IsChecked = true;
                    }
                    else
                    {
                        checkBox.IsChecked = false;
                    }
                }
            }
        }

        private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
        {
            if (this.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
            {
                this.SetExistingValues(this.List);
            }
        }

    }
}
